#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "requetes.h"
#include "client.h"

void winstart(void)
{
#ifdef WIN32
    WSADATA wsa;
    int err = WSAStartup(MAKEWORD(2, 2), &wsa);
    if(err < 0)
    {
        puts("WSAStartup failed !");
        exit(EXIT_FAILURE);
    }
#endif
}

void winstop(void)
{
#ifdef WIN32
    WSACleanup();
#endif
}

void cerveau(const char *address, const char *name)
{
    SOCKET sock = debutConnexion(address);
    envoyerAuth(sock, name);
    puts(name);
    envoyerPut(sock, name);
    puts("transfert accomplis");
    while(1);
    finConnexion(sock);
}

int debutConnexion(const char *address)
{
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    SOCKADDR_IN sin = { 0 };
    struct hostent *hostinfo;

    if(sock == INVALID_SOCKET)
    {
        perror("socket()");
        exit(errno);
    }

    hostinfo = gethostbyname(address);
    if (hostinfo == NULL)
    {
        fprintf (stderr, "Unknown host %s.\n", address);
        exit(EXIT_FAILURE);
    }

    sin.sin_addr = *(IN_ADDR *) hostinfo->h_addr;
    sin.sin_port = htons(PORT);
    sin.sin_family = AF_INET;

    if(connect(sock,(SOCKADDR *) &sin, sizeof(SOCKADDR)) == SOCKET_ERROR)
    {
        perror("connect()");
        exit(errno);
    }

    return sock;
}

void finConnexion(int sock)
{
    closesocket(sock);
}

int lireTexte(SOCKET sock, char *buffer)
{
    int n = 0;

    if((n = recv(sock, buffer, TAILLE_BUFFER - 1, 0)) < 0)
    {
        perror("recv()");
        exit(errno);
    }

    buffer[n] = 0;

    return n;
}

void ecrireTexte(SOCKET sock, const char *buffer)
{
    if(send(sock, buffer, strlen(buffer), 0) < 0)
    {
        perror("swinstop()");
        exit(errno);
    }
}

int lireBinaire(SOCKET sock, void *buffer, int taille){

    int err = recv(sock, buffer, taille, 0);

    puts("je recoit");
    if ( 0 == err ){
        fprintf(stderr, "erreur recv\n");
    }
    return err;
}

int ecrireBinaire(SOCKET sock, void * buffer, int taille)
{
    int err =send(sock, buffer, taille, 0);
    printf("j'envoie %d\n", taille);
    if ( 0 == err ){
        fprintf(stderr, "erreur recv\n");
    }
    return err;

}

